package com.wzy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wzy.exception.SystemException;
import com.wzy.util.RedisCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import static com.wzy.constant.RedisConstants.REDIS_LOGIN_KEY;
import static com.wzy.constant.SystemConstants.ADMIN_ROLE;
import static com.wzy.constant.SystemConstants.TOKEN_KEY;
import static com.wzy.enums.AppHttpCodeEnum.NO_OPERATOR_AUTH;

/**
 * 用户通用方法
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserCommonService
{
    private final RedisCache redisCache;

    public String getToken(HttpServletRequest httpServletRequest)
    {
        return httpServletRequest.getHeader(TOKEN_KEY);
    }

    /**
     * 获取Redis LoginUser
     */
    public JSONObject getRedisLoginUser(HttpServletRequest httpServletRequest)
    {
        String token = getToken(httpServletRequest);
        Object cacheObject = redisCache.getCacheObject(REDIS_LOGIN_KEY + token);
        String value = String.valueOf(cacheObject);
        return JSON.parseObject(value);
    }

    /**
     * 获取Redis User
     */
    public JSONObject getRedisUser(HttpServletRequest httpServletRequest)
    {
        JSONObject redisLoginUser = getRedisLoginUser(httpServletRequest);
        return redisLoginUser.getJSONObject("user");
    }

    /**
     * 获取Redis UserId
     */
    public Long getRedisUserId(HttpServletRequest httpServletRequest)
    {
        return getRedisUser(httpServletRequest).getLong("id");
    }

    /**
     * 获取Redis UserRole
     */
    public String getRedisUserRole(HttpServletRequest httpServletRequest)
    {
        return getRedisUser(httpServletRequest).getString("userRole");
    }

    /**
     * 是否管理员
     */
    public boolean isAdmin(HttpServletRequest httpServletRequest)
    {
        return getRedisUserRole(httpServletRequest).equals(ADMIN_ROLE);
    }

    /**
     * 校验权限
     */
    public void checkRole(HttpServletRequest httpServletRequest)
    {
        if (!isAdmin(httpServletRequest))
        {
            throw new SystemException(NO_OPERATOR_AUTH);
        }
    }

}
